/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author Joe Maisel
 *
 */
public class FileUploadSizeTestInterceptor implements Interceptor
{
	private int maxFileSize;
	private static final Log lager = LogFactory.getLog( FileUploadSizeTestInterceptor.class );
	
	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
	 */
	@Override
	public void init()
	{
		lager.info( "\n\n\n\nworking!!!!!!!!!" );
		
		try
		{
			Properties defaults = new Properties();
			defaults.load(  this.getClass().getClassLoader().getResourceAsStream( "org/apache/struts2/default.properties" ) );
			maxFileSize = Integer.parseInt( defaults.getProperty( "struts.multipart.maxSize" ) );
			
			InputStream is = this.getClass().getClassLoader().getResourceAsStream( "struts.properties" );
			if( is != null )
			{
				Properties overrides = new Properties();
				overrides.load( is );
				maxFileSize = Integer.parseInt( overrides.getProperty( "struts.multipart.maxSize" ) );
			}
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}
	}

	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept( ActionInvocation ai ) throws Exception
	{
		lager.info( "\n\n\n\nintercept!!!!!!!!!" );
		
	    HttpServletRequest request = (HttpServletRequest) ServletActionContext.getRequest();
	    int length = request.getContentLength();
	    
		if( length > 0 && length > maxFileSize ){
			return Action.ERROR;
		}
		
		return ai.invoke();
	}
	
	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
	 */
	@Override
	public void destroy()
	{
	}


	private static final long serialVersionUID = -1953497826147920279L;
}
